#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>

// gcc 04_tcp_server.c -o tcp_server
// ./tcp_server

int main(int argc, char const *argv[])
{
    //创建tcp 服务器的监听套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0) {
        perror("socket");
        return 0;
    }

    //bind绑定固定的port、ip地址信息
    struct sockaddr_in my_addr;
    bzero(&my_addr, sizeof(my_addr));
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(8000);
    my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    int ret = bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr));
    if(ret == -1) {
        perror("bind");
        return 0;
    }

    //监听套接字 创建连接队列
    ret = listen(sockfd, 10);
    if(ret == -1) {
        perror("listen");
        return 0;
    }

    //提取客户端的连接
    while(1) {
        printf("----------------------------------------------------- \n");
        //一次只能提取一個客戶端
        struct sockaddr_in cli_addr;
        socklen_t cli_len = sizeof(cli_addr);
        int cfd = accept(sockfd, (struct sockaddr *)&cli_addr, &cli_len);
        if(cfd < 0) {
            //提取失败
            perror("accept\n");
            break;
        } else {
            char ip[16]="";
            unsigned short port=0;
            inet_ntop(AF_INET, &cli_addr.sin_addr.s_addr, ip, 16);
            port = ntohs(cli_addr.sin_port);
            //打印客户端的信息
            printf("客户端:%s %d connected\n", ip, port);

            while(1) {
                //获取客户端的请求
                unsigned char recv_buf[1500]="";
                unsigned char send_buf[64]="Hi client";
                int len = recv(cfd, recv_buf, sizeof(recv_buf), 0);
                if(len == 0) {
                    printf("客户端 off \n");
                    //客户端已经关闭
                    //关闭与客户端连接的套接字
                    close(cfd);
                    break;
                }
                printf("接收客户端消息：%s \n", recv_buf);
                //应答客户端
                send(cfd, send_buf, 64, 0);
            }
        }
    }

    //关闭监听套接字
    close(sockfd);
    return 0;
}